<?php

namespace App\Http\Controllers\Home;

use App\Http\Controllers\Core\BaseController;
use App\Models\Member;
use App\Models\Sms;


use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Input;
use function MongoDB\BSON\toJSON;

class AuthController extends BaseController
{
    public function register()
    {
        return view('home.auth.register');
    }


    public function login()
    {
        return view('home.auth.login');
    }

    public function code(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'mobile' => 'required|max:11|string',
        ]);
        if ($validator->fails()) {
            $data = [401, $validator->errors()];
            return $data;
        }
        //判断是否在规定时间内进行验证
        $now = time();
        $express = $now - 60;
        $sms = Sms::where('create_time', '>', $express)->limit(1)->get();
        if ($sms->first()) {
            $data = [402, '暂时不能发送信息'];
            return $data;
        }
        /*
         * 发送短信信息
         * */
        $code = rand(100000, 999999);

        //模拟发送
        $code = 8475;
        $model = new Sms();
        $model->mobile = $request->get('mobile');
        $model->code = $code;
        $model->message = '';
        $model->create_time = $now;
        if ($model->save()) {
            return [0, '成功'];
        } else {
            return [400, '插入失败'];
        }
    }

    public function ajaxValidate(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'mobile' => 'required|max:11|string',
        ]);
        if ($validator->fails()) {
            return $this->retRequestJson(0, '账号有误');
        }
        $mobile = $request->get('mobile');
        $password = $request->get('password');
        //获取当前用户是否存在
        $member = Member::where(['username' => $mobile])->get();
        if (!$member = $member->first()) {
            return $this->retRequestJson(0, '账号或者密码有误');
        }
        if (password_verify($password, $member->password)) {
            session(['member' => json_encode($member)]);
            return $this->retRequestJson(1, '成功');
        }
        return $this->retRequestJson(0, '账号不存在');
    }
}